package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.pojo.Bumenguanli;
import com.qf.pojo.Permsetting;
import com.qf.pojo.Usermanager;
import com.qf.service.DeptService;
import com.qf.service.PermsettingService;
import com.qf.service.UsermanagerService;
import com.qf.utils.ExportExcelUtils;
import com.qf.utils.RandomUtil;
import com.qf.utils.vo.ResultVO;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2019/11/19 0019
 * DT
 * qmxc
 * 行到水穷处 坐看云起时
 * 用户管理Controller模块
 */
@Controller
@RequestMapping("/user")
public class UsermanagerController {
    @Autowired
    private UsermanagerService usermanagerService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private PermsettingService permsettingService;

//    //1.登录
//    @RequestMapping("/login")
//    public String login(String username, String password, HttpSession session){
//        Usermanager usermanager = usermanagerService.login(username, password);
//        if (usermanager==null){
//            //登录失败，用户名或密码错误
//            return "login";
//        }
//        //登录成功
//        //将用户信息保存到Session中
//        session.setAttribute("user", usermanager);
//        //重定向到首页
//        return "redirect:/index.jsp";
//    }

    //shiro会自动进行登录认证：要求账户名为:username;密码为:password
    //以下是处理登录失败的各种异常情况：
    @RequestMapping("/login")
    public String login(HttpServletRequest request) throws  Exception{
        //从FormAuthenticationFilter获得验证失败的错误信息
        String failure = (String)request.getAttribute("shiroLoginFailure");
        if(failure!=null){
            if(UnknownAccountException.class.getName().equals(failure)){
                throw new Exception("用户名错误");
            }else if(IncorrectCredentialsException.class.getName().equals(failure)){
                throw new Exception("密码错误");
            }else {
                throw new Exception("未知错误");
            }
        }
        return "login";
    }
//
//    //2.清除Session登录信息
//    @RequestMapping("/logout")
//    public String logout(HttpSession session){
//        //清除Session信息
//        session.invalidate();
//        //重定向到登录页
//        return "redirect:/login.jsp";
//    }

    //3.系统管理-->用户管理-->用户信息列表显示与查询
    @RequestMapping("/getusers")
    @RequiresPermissions("user:getUsers")
    public String list(@RequestParam(defaultValue = "1")Integer index,
                       @RequestParam(defaultValue = "3")Integer page, Model model,
                       String username,String pname,String bname){

        //0.封装参数
        Map map=new HashMap();
        map.put("index", index);
        map.put("page", page);
        //用户姓名
        map.put("username", username);
        //用户角色名
        map.put("pname", pname);
        //用户部门名
        map.put("bname", bname);

        //1.查询
        PageInfo<Usermanager> pageInfo=usermanagerService.findAllByLimitAndExample(map);
        //2.将查询到的信息放入Request域中
        //2.1pageInfo对象
        model.addAttribute("pageInfo", pageInfo);
        //2,2数据回显信息
        model.addAttribute("username", username);
        model.addAttribute("pname", pname);
        model.addAttribute("bname", bname);
        //3.返回展示页面
        return "resource/demo2/list";
    }

    //4.跳转到添加用户页面(查询出全部部门信息)
    @RequestMapping("/add-ui")
    public String UserAdd(Model model){
        List<Bumenguanli> deptList = deptService.findAll();
        model.addAttribute("deptList", deptList);
        return "resource/demo2/add";
    }

    //5.根据部门ID查询该部门所有职位信息
    @RequestMapping("/getRoles")
    @ResponseBody
    public List<Permsetting> getRoles(Integer deptId,Model model){
        List<Permsetting> roleList = permsettingService.findAllRolesByDeptId(deptId);
        return roleList;
    }

    //6,新增用户
    @RequestMapping("/add")
    public String addUser(Usermanager user){
        //添加
        int count = usermanagerService.insert(user);
        if(count==1){
            //添加成功，返回首页
            return "redirect:/user/getusers";
        }else {
            return "redirect:/user/add-ui";
        }
    }

    //7.新增用户时，校验用户编号是否重复
    @RequestMapping("/check-userid")
    @ResponseBody
    public ResultVO checkUserID(Integer userid){
        if (userid==null){
            //编号为空
            return new ResultVO(2,"用户编号为空！",null);

        }
        Long count = usermanagerService.findUserCountByUserId(userid);
        if (count>=1){
            return new ResultVO(1,"用户编号已存在！",null);
        }else {
            return new ResultVO(0,"用户编号可用！",null);

        }
    }

    //8.跳转到用户信息修改页
    @RequestMapping("/update-ui")
//    @RequiresPermissions("user:updateUI")
    public String updateUI(Integer id,Model model){
        //根据id查询出用户信息
        Usermanager user = usermanagerService.selectByPrimaryKey(id);
        //查询出全部部门信息
        List<Bumenguanli> deptList = deptService.findAll();
        //根据部门id查询出该部门全部职位信息
        List<Permsetting> roleList = permsettingService.findAllRolesByDeptId(user.getUserappartment());
        //将数据放到请求域中
        model.addAttribute("user", user);
        model.addAttribute("deptList", deptList);
        model.addAttribute("roleList", roleList);
        //转发页面
        return "resource/demo2/update";
    }

    //9.执行用户修改
    @RequestMapping("/update")
    @RequiresPermissions("user:update")
    public String update(Usermanager user){
        //执行修改
        int count = usermanagerService.updateByPrimaryKeySelective(user);
        if (count==1){
            //修改成功
            return "redirect:/user/getusers";
        }else {

            //修改失败
            return "redirect:/user/update-ui?id="+user.getId();
        }
    }

    //10、单行用户删除(逻辑删除：修改用户状态为删除)
    @RequestMapping("/delete-one")
    @RequiresPermissions("user:deleteOne")
    public void deleteOneByid(Integer id, HttpServletResponse response){
        //调用Service修改用户状态为删除状态
        int count=usermanagerService.updateStateToDelete(id);
        //构建响应流，给用户提示，返回类型必需为void
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            if (count==1){
                //删除成功
                writer.print("<script>alert('删除成功');location.href='/user/getusers'</script>");

            }else {
                //删除失败
                writer.print("<script>alert('删除失败');location.href='/user/getusers'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //11.多行删除(逻辑删除复选框选择的所有用户)+导出数据
    @RequestMapping("/delete-checked")
    @RequiresPermissions("user:deleteChecked")
    public void deleteChecked(Integer[] uid,HttpServletResponse response,String method){
        //method相当于鉴别器，根据传入的method不同，进行不同处理
        //构建响应流，给用户提示，返回类型必需为void
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;

        //调用Service执行批量删除
        if (method.equals("delete")){
            int count = usermanagerService.updateCheckedUsersStateToDelete(uid);
            //判断删除是否成功
            try {
                writer = response.getWriter();
                if (count>=1){
                    //删除成功
                    writer.print("<script>alert('删除成功');location.href='/user/getusers'</script>");

                }else {
                    //删除失败
                    writer.print("<script>alert('删除失败');location.href='/user/getusers'</script>");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //将用户id对应的用户数据导出为Excel
        else if (method.equals("export")){
            //查询被选中id的用户信息
            List<Usermanager> userList=usermanagerService.findByIds(uid);
            //利用工具类导出
            //构建第一列
            ExportExcelUtils.createFirst("用户信息");
            //构建其他列
            ExportExcelUtils.createOthers(userList);
            //构建输出流，导出到指定位置
            try {
                //随机生成文件名
                String fileName=RandomUtil.dataRandom()+".xls";
                //导出Excel
                ExportExcelUtils.export(new FileOutputStream("f://"+fileName));
                //导出成功,已下载框的方式响应给页面
                //设置响应头，控制浏览器下载该文件
                response.setContentType("application/x-download");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                ExportExcelUtils.export(response.getOutputStream());
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("application/ms-excel");
//                response.setHeader("Content-Disposition",
//                        "inline;filename="+
//                                new String(fileName.getBytes("utf-8"),"UTF-8"));

//                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName+".xls", "UTF-8"));
//                //读取要下载的文件，保存到文件输入流
//                FileInputStream in = new FileInputStream("f://"+fileName );
//                //创建输出流
//                OutputStream out = response.getOutputStream();
//                //创建缓冲区
//                byte buffer[] = new byte[1024];
//                int len = 0;
//                //循环将输入流中的内容读取到缓冲区当中
//                while((len=in.read(buffer))>0){
//                    //输出缓冲区的内容到浏览器，实现文件下载
//                    out.write(buffer, 0, len);
//                    }
//                //关闭文件输入流
//                in.close();
//                //关闭输出流
//                out.close();
//                writer.print("<script>alert('导出成功！');location.href='/user/getusers'</script>");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

